package cn.jlearn.proxy.server.utils;

import cn.hutool.core.util.StrUtil;
import cn.jlearn.proxy.common.utils.PropertiesUtil;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RKeys;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.TransportMode;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/7/19 12:11 下午
 */
public class RedissonUtil {

    private static volatile RedissonUtil redissonUtil;

    private final RedissonClient redissonClient;

    private static final String HOST = PropertiesUtil.getProperty("redis.host");

    private static final Integer PORT = Integer.parseInt(PropertiesUtil.getProperty("redis.port"));

    private static final Integer DATABASE = Integer.parseInt(PropertiesUtil.getProperty("redis.database"));

    private static final String PASSWORD = PropertiesUtil.getProperty("redis.password");

    public RedissonUtil() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + HOST + ":" + PORT)
                .setDatabase(DATABASE)
                .setIdleConnectionTimeout(10000)
                .setConnectTimeout(10000)
                .setTimeout(3000)
                .setRetryAttempts(3)
                .setRetryInterval(1500)
                .setSubscriptionsPerConnection(5)
                .setClientName(null)
                .setSubscriptionConnectionMinimumIdleSize(1)
                .setSubscriptionConnectionPoolSize(50)
                .setConnectionMinimumIdleSize(32)
                .setConnectionPoolSize(64)
                .setDnsMonitoringInterval(5000);
        if (!StrUtil.isBlank(PASSWORD)) {
            config.useSingleServer().setPassword(PASSWORD);
        }
        config.setThreads(0);
        config.setNettyThreads(0);
        config.setCodec(JsonJacksonCodec.INSTANCE);
        config.setTransportMode(TransportMode.NIO);
        this.redissonClient = Redisson.create(config);
    }

    public static RedissonUtil getInstance() {
        if (redissonUtil == null) {
            synchronized (RedissonUtil.class) {
                if (redissonUtil == null) {
                    redissonUtil = new RedissonUtil();
                }
            }
        }
        return redissonUtil;
    }

    public void del(String key) {
        RKeys keys = redissonClient.getKeys();
        keys.delete(key);
    }

    public void set(String key, String value) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        bucket.set(value);
    }

    public String get(String key) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

}
